package cn.ickck.law_paper_final.controller;


import cn.ickck.law_paper_final.model.entity.HouseLoan;
import cn.ickck.law_paper_final.model.entity.HouseLoanBatch;
import cn.ickck.law_paper_final.model.response.HouseLoanBatchResponse;
import cn.ickck.law_paper_final.service.HouseLoanBatchService;
import cn.ickck.law_paper_final.service.HouseLoanService;
import cn.ickck.law_paper_final.utils.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

/**
 * @Author: ck
 * @Description:
 * @Date: Create in 12:20 2020/11/7
 */
@RestController
@RequestMapping("/api/v2/pub/house_loan_batch")
public class HouseLoanBatchController {
    @Autowired
    private HouseLoanBatchService houseLoanBatchService;
    @Autowired
    private HouseLoanService houseLoanService;

    @RequestMapping("selectByPage")
    public JsonData selectByPage(Integer page)
    {
        int count = houseLoanBatchService.count();
        HouseLoanBatchResponse houseLoanBatchResponse = new HouseLoanBatchResponse();
        houseLoanBatchResponse.setCount(count);
        int start =count-page*20>0?count-page*20:0;
        int end = count-(page-1)*20>0?count-(page-1)*20:count;
        houseLoanBatchResponse.setHouseLoanBatches(houseLoanBatchService.selectByPage(start,end));
        return JsonData.buildSuccess(houseLoanBatchResponse);
    }

    //模糊查询
    @RequestMapping("selectByName")
    public JsonData selectByName(@Param("key") String key,@Param("page")int page)
    {
        HouseLoanBatchResponse houseLoanBatchResponse  = new HouseLoanBatchResponse();
        List<HouseLoanBatch> houseLoanBatchList = houseLoanBatchService.selectByName(key);
        int start = PageHelperUtils.getStart(houseLoanBatchList.size(),page);
        int end  = PageHelperUtils.getEnd(houseLoanBatchList.size(),page);
        List<HouseLoanBatch> houseLoanBatchList1 = new ArrayList<>();
        for(int i = start;i<end;i++)
        {
            houseLoanBatchList1.add(houseLoanBatchList.get(i));
        }
        houseLoanBatchResponse.setCount(houseLoanBatchList.size());
        houseLoanBatchResponse.setHouseLoanBatches(houseLoanBatchList1);
        return JsonData.buildSuccess(houseLoanBatchResponse);
    }

    @Transactional
    @RequestMapping("deleteById")
    public JsonData deleteById(Integer id)
    {

        //还应该把这一批次的所有信息都删除
        //根据id查询到key
        String key = houseLoanBatchService.selectKeyById(id).getKey();
        //根据key删除相应信息

        //需要引入事务 以后再说
        houseLoanService.deleteByKey(key);
        houseLoanBatchService.deleteById(id);


        return JsonData.buildSuccess("删除成功");
    }

    @RequestMapping("update")
    public JsonData update(@RequestBody HouseLoanBatch houseLoanBatch)
    {

        System.out.println(houseLoanBatch.getName()+houseLoanBatch.getKey());

        //更新校验
        houseLoanBatchService.update(houseLoanBatch);
        return JsonData.buildSuccess("更新成功");

    }


    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestBody HouseLoanBatch houseLoanBatch)throws Exception
    {
        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());
        ExcelUtils.exportExcel(houseLoans,HouseLoan.class,houseLoanBatch.getName()+".xlsx",response);
    }

     //强制执行申请书（房贷）
    @RequestMapping("exportWord")
    public void exportWord(HttpServletResponse response, @RequestBody HouseLoanBatch houseLoanBatch) throws Exception {
        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());
        Map data = new HashMap<>();
        System.out.println("调用方法");
        data.put("houseLoans", houseLoans);
        response.setHeader("content-Type", "application/msword");
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(getClass(), "/templates");
        Template template = null;
        try {
            template = cfg.getTemplate("强制执行申请书-房贷.ftl", "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }


        OutputStream outputStream = response.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);


        try {
            DownLoadFileUtil.setResponseHeader(response, "强制执行申请书-房贷");
            template.process(data, outputStreamWriter);
//            System.out.println(outputStreamWriter);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("exportZip")
    public void exportZip(HttpServletResponse httpServletResponse,@RequestBody HouseLoanBatch houseLoanBatch) throws Exception
    {

        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());

        List<File> files = new ArrayList<>();
        for (HouseLoan houseLoan:houseLoans) {

            Map data = new HashMap<>();
            List<HouseLoan> houseLoan1 = new ArrayList<>();
            houseLoan1.add(houseLoan);
            data.put("houseLoans",houseLoan1);

            String filePath = FileUtils.getWordPath();
            //文件唯一名称
            String fileOnlyName = houseLoan.getName() + UUID.randomUUID().toString() + ".doc";
            /** 生成word  数据包装，模板名，文件生成路径，生成的文件名*/

            WordUtil.createWord(data, "强制执行申请书-房贷.ftl", filePath, fileOnlyName);
            File f = new File(filePath + File.separator + fileOnlyName);
            files.add(f);
        }

        //调用压缩
        String time = System.currentTimeMillis() + "";
        String zipFilePath = FileUtils.getWordPath() + File.separator + time + ".zip";
        try {
            ZipUtil.create(zipFilePath, files);
            //下载文件
            File f = new File(zipFilePath);
            if (f.exists()) {
                ZipUtil.downloadZip(f, httpServletResponse);
//                DownLoadFileUtil.setResponseHeader(response,zipFilePath);
            } else {
                System.out.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (File file : files) {
            file.delete();
        }


    }


    //个人有抵押无担保（房贷）
    @RequestMapping("exportWord_1")
    public void exportWord_1(HttpServletResponse response, @RequestBody HouseLoanBatch houseLoanBatch) throws Exception {
        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());
        Map data = new HashMap<>();
        System.out.println("调用方法");
        data.put("houseLoans", houseLoans);
        response.setHeader("content-Type", "application/msword");
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(getClass(), "/templates");
        Template template = null;
        try {
            template = cfg.getTemplate("民事起诉状-房贷-个人有抵押无担保.ftl", "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }


        OutputStream outputStream = response.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);


        try {
            DownLoadFileUtil.setResponseHeader(response, "民事起诉状-房贷-个人有抵押无担保.ftl");
            template.process(data, outputStreamWriter);
//            System.out.println(outputStreamWriter);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("exportZip_1")
    public void exportZip_1(HttpServletResponse httpServletResponse,@RequestBody HouseLoanBatch houseLoanBatch) throws Exception
    {

        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());

        List<File> files = new ArrayList<>();
        for (HouseLoan houseLoan:houseLoans) {

            Map data = new HashMap<>();
            List<HouseLoan> houseLoan1 = new ArrayList<>();
            houseLoan1.add(houseLoan);
            data.put("houseLoans",houseLoan1);

            String filePath = FileUtils.getWordPath();
            //文件唯一名称
            String fileOnlyName = houseLoan.getName() + UUID.randomUUID().toString() + ".doc";
            /** 生成word  数据包装，模板名，文件生成路径，生成的文件名*/

            WordUtil.createWord(data, "民事起诉状-房贷-个人有抵押无担保.ftl", filePath, fileOnlyName);
            File f = new File(filePath + File.separator + fileOnlyName);
            files.add(f);
        }

        //调用压缩
        String time = System.currentTimeMillis() + "";
        String zipFilePath = FileUtils.getWordPath() + File.separator + time + ".zip";
        try {
            ZipUtil.create(zipFilePath, files);
            //下载文件
            File f = new File(zipFilePath);
            if (f.exists()) {
                ZipUtil.downloadZip(f, httpServletResponse);
//                DownLoadFileUtil.setResponseHeader(response,zipFilePath);
            } else {
                System.out.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (File file : files) {
            file.delete();
        }


    }



    //民事起诉状-房贷-个人有抵押有担保

    @RequestMapping("exportWord_2")
    public void exportWord_2(HttpServletResponse response, @RequestBody HouseLoanBatch houseLoanBatch) throws Exception {
        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());
        Map data = new HashMap<>();
        System.out.println("调用方法");
        data.put("houseLoans", houseLoans);
        response.setHeader("content-Type", "application/msword");
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(getClass(), "/templates");
        Template template = null;
        try {
            template = cfg.getTemplate("民事起诉状-房贷-个人有抵押有担保.ftl", "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }


        OutputStream outputStream = response.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);


        try {
            DownLoadFileUtil.setResponseHeader(response, "民事起诉状-房贷-个人有抵押有担保.ftl");
            template.process(data, outputStreamWriter);
//            System.out.println(outputStreamWriter);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("exportZip_2")
    public void exportZip_2(HttpServletResponse httpServletResponse,@RequestBody HouseLoanBatch houseLoanBatch) throws Exception
    {

        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());

        List<File> files = new ArrayList<>();
        for (HouseLoan houseLoan:houseLoans) {

            Map data = new HashMap<>();
            List<HouseLoan> houseLoan1 = new ArrayList<>();
            houseLoan1.add(houseLoan);
            data.put("houseLoans",houseLoan1);

            String filePath = FileUtils.getWordPath();
            //文件唯一名称
            String fileOnlyName = houseLoan.getName() + UUID.randomUUID().toString() + ".doc";
            /** 生成word  数据包装，模板名，文件生成路径，生成的文件名*/

            WordUtil.createWord(data, "民事起诉状-房贷-个人有抵押有担保.ftl", filePath, fileOnlyName);
            File f = new File(filePath + File.separator + fileOnlyName);
            files.add(f);
        }

        //调用压缩
        String time = System.currentTimeMillis() + "";
        String zipFilePath = FileUtils.getWordPath() + File.separator + time + ".zip";
        try {
            ZipUtil.create(zipFilePath, files);
            //下载文件
            File f = new File(zipFilePath);
            if (f.exists()) {
                ZipUtil.downloadZip(f, httpServletResponse);
//                DownLoadFileUtil.setResponseHeader(response,zipFilePath);
            } else {
                System.out.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (File file : files) {
            file.delete();
        }


    }


    //夫妻债务有抵押无担保

    @RequestMapping("exportWord_3")
    public void exportWord_3(HttpServletResponse response, @RequestBody HouseLoanBatch houseLoanBatch) throws Exception {
        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());
        Map data = new HashMap<>();
        System.out.println("调用方法");
        data.put("houseLoans", houseLoans);
        response.setHeader("content-Type", "application/msword");
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(getClass(), "/templates");
        Template template = null;
        try {
            template = cfg.getTemplate("民事起诉状-房贷-夫妻债务有抵押无担保.ftl", "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }


        OutputStream outputStream = response.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);


        try {
            DownLoadFileUtil.setResponseHeader(response, "民事起诉状-房贷-夫妻债务有抵押无担保.ftl");
            template.process(data, outputStreamWriter);
//            System.out.println(outputStreamWriter);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("exportZip_3")
    public void exportZip_3(HttpServletResponse httpServletResponse,@RequestBody HouseLoanBatch houseLoanBatch) throws Exception
    {

        List<HouseLoan> houseLoans = houseLoanService.selectByNameOrKey(houseLoanBatch.getKey());

        List<File> files = new ArrayList<>();
        for (HouseLoan houseLoan:houseLoans) {

            Map data = new HashMap<>();
            List<HouseLoan> houseLoan1 = new ArrayList<>();
            houseLoan1.add(houseLoan);
            data.put("houseLoans",houseLoan1);

            String filePath = FileUtils.getWordPath();
            //文件唯一名称
            String fileOnlyName = houseLoan.getName() + UUID.randomUUID().toString() + ".doc";
            /** 生成word  数据包装，模板名，文件生成路径，生成的文件名*/

            WordUtil.createWord(data, "民事起诉状-房贷-夫妻债务有抵押无担保.ftl", filePath, fileOnlyName);
            File f = new File(filePath + File.separator + fileOnlyName);
            files.add(f);
        }

        //调用压缩
        String time = System.currentTimeMillis() + "";
        String zipFilePath = FileUtils.getWordPath() + File.separator + time + ".zip";
        try {
            ZipUtil.create(zipFilePath, files);
            //下载文件
            File f = new File(zipFilePath);
            if (f.exists()) {
                ZipUtil.downloadZip(f, httpServletResponse);
//                DownLoadFileUtil.setResponseHeader(response,zipFilePath);
            } else {
                System.out.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (File file : files) {
            file.delete();
        }


    }



}
